package org.example.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.Exception.RollBackException;
import org.example.SpringSecurityTestApplication;
import org.example.dao.BookContentDao;
import org.example.dao.BookDao;
import org.example.dao.SlideShowDao;
import org.example.domain.*;
import org.example.domain.response.ResponseResult;
import org.example.services.BookService;
import org.example.utils.FileUtil;
import org.example.utils.PageConvertPageBeanUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;


@Slf4j  //日志
@Transactional  //事务回滚
@Service
public class BookServiceImpl extends ServiceImpl<BookDao,Book> implements BookService {

    @Resource
    private BookDao bookDao;
    @Resource
    private BookContentDao bookContentDao;
    @Resource
    private SlideShowDao slideShowDao;

    //    查询所有
    public List<Book> getAllBook(){
        List<Book> books = bookDao.selectList(null);
        for (Book book : books) {
            List<String> bookType = bookDao.getBookType(book.getBookId());
            book.setType(bookType);
        }
        return books;
    }
    //      删除书籍
    @Override
    public ResponseResult deleteBook(Integer id) {
        try {
            Book book = bookDao.selectById(id);
            if(book==null){
                log.warn("书籍删除：书籍基本信息查询失败");
                throw new RollBackException("无该书籍，请刷新");
            }
            bookDao.deleteById(id);
            bookDao.deleteBookTypeByBookId(book.getBookId());
            bookContentDao.deleteBookContentByBookId(id);
            return ResponseResult.success("书籍删除成功");
        }catch (Exception e){
            e.printStackTrace();
            log.warn("删除书籍失败");
            throw  new RollBackException("删除书籍失败");
        }
    }


    //      添加书籍
    @Override
    public ResponseResult saveBook(Book book) {
        try {
            book.getData().setBookId(book.getBookId());
            bookDao.insert(book);
            bookDao.setBookType(book.getBookId(),book.getType());
            book.getData().setBookId(book.getBookId());
            bookContentDao.ContentInsert(book.getData());
            return ResponseResult.success("添加书籍成功",book);
        }catch (Exception e){
            e.printStackTrace();
            log.warn("添加书籍失败");
            throw  new RollBackException("添加书籍失败");
        }
    }

    //    修改书籍
    @Override
    public ResponseResult updateBook(Book book) {
        Book bookRes = bookDao.selectById(book.getBookId());
        if(bookRes==null){
            log.warn("书籍修改：书籍基本信息查询失败");
            throw new RollBackException("无该问题信息，请刷新");
        }try {
//        修改书籍类型
            bookDao.updateById(book);
//        书籍类型全删后新加
            if(book.getType()!=null){
                bookDao.deleteBookTypeByBookId(book.getBookId());
                bookDao.setBookType(book.getBookId(),book.getType());
            }
//        通过bookId查询bookContentId，在通过bookContentId更新
            if(book.getData()!=null){
                BookContent content = bookContentDao.getContentByBookId(book.getBookId());
                BookContent bookContent=book.getData();
                bookContent.setBookId(content.getBookId());
                bookContentDao.updateByBookId(bookContent);
            }
            log.info(bookRes.getBookId()+"书籍修改成功");
            return ResponseResult.success("书籍修改成功");
        }catch (Exception e){
            e.printStackTrace();
            log.warn("书籍修改失败");
            throw new RollBackException("书籍修改失败");
        }
    }

    //    通过id查询
    @Override
    public ResponseResult getBook(Integer bookId) {
        try {
            Book book=bookDao.selectById(bookId);
            BookContent bookContent=bookContentDao.getContentByBookId(bookId);
            List<String> bookType = bookDao.getBookType(bookId);
            book.setData(bookContent);
            book.setType(bookType);
            return ResponseResult.success("通过id查询成功",book);
        } catch (NullPointerException e){
            log.warn(bookId+":通过id查询失败，case：无该书籍id数据");
            throw new RollBackException("无该书籍数据");
        }catch (Exception e){
            log.warn(bookId +"：通过id查询失败,case:"+e.getCause().getMessage());
            throw new RollBackException("查询书籍失败");
        }
    }

    //      分页
    @Override
    public ResponseResult getPage(int currentPage, int pageSize) {
        Page<Book> page = new Page(currentPage, pageSize);
//        封装
        Page<Book> bookPage = bookDao.selectPage(page, null);
        PageBean<Book> pageBean = PageConvertPageBeanUtil.convert(bookPage);
        List<Book> books = pageBean.getRows();
        for (Book book : books) {
            List<String> bookType = bookDao.getBookType(book.getBookId());
            book.setType(bookType);
        }
        log.info("分页查询书籍：成功{}",pageBean);
        return ResponseResult.success("分页查询书籍成功",pageBean);
    }



    //    通过type查询
    @Override
    public ResponseResult getTypeByPage(String type, int pageSize, int currentPage) {
        try {
            List<Book> bookByType = bookDao.getBookByType(type, (currentPage-1)*pageSize, pageSize);
            PageBean<Book> pageBean = new PageBean<>();
            pageBean.setRows(bookByType);
            pageBean.setPageSize(pageSize);
            pageBean.setCurrentPage(currentPage);
            List<Integer> integers = bookDao.selectByType(type);
            int integer = integers.size();
            pageBean.setTotalData(integer);
            pageBean.setTotalPages((integer + pageSize)/pageSize);
            log.info("按书籍类型分页查询成功");
            return ResponseResult.success("分页查询类型成功",pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("按书籍类型分页查询失败");
            return null;
        }
    }

    //    通过type查询
    public Book getType(String type){
        List<Integer> book_id=bookDao.selectByType(type);
        Book book= bookDao.selectById((Serializable) book_id);
        if(book == null){
            return null;
        }
        BookContent bookContent= (BookContent) bookContentDao.selectByBookId2(book_id);
        if(bookContent==null){
            return null;
        }
        List<String> types=bookDao.getBookType1(book_id);
        if(types==null){
            return null;
        }
        book.setType(types);
        book.setData(bookContent);
        return book;
    }

    //    通过name查询
    @Override
    public ResponseResult getNameByPage(String name, int pageSize, int currentPage) {
        try {
            Page<Book> page = new Page<>(currentPage,pageSize);
            QueryWrapper<Book> wrapper = new QueryWrapper<>();
            wrapper.like("name",name);
            Page<Book> bookPage = bookDao.selectPage(page, wrapper);
            PageBean<Book> pageBean=PageConvertPageBeanUtil.convert(bookPage);
            log.info("按商品名称分页查询成功");
            return ResponseResult.success("分页查询名字成功",pageBean);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("按商品名称分页查询失败");
            return null;
        }
    }

    @Override
    public ResponseResult uploadBookCover(MultipartFile file, int bookId) {
        Book book = bookDao.selectById(bookId);
        if(book == null){
            return ResponseResult.failed("书籍不存在，请刷新后重试");
        }
        ApplicationHome applicationHome = new ApplicationHome(SpringSecurityTestApplication.class);
        //将文件保存在当前项目同目录中的images中
        //打包前是当前java文件目录下，打包后是在项目目录下
        String path = applicationHome.getDir().getAbsolutePath()
                + File.separator  + "images"
                + File.separator  + "bookCover";

        if(file.isEmpty()){
            return ResponseResult.failed("文件为空");
        }

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fileNameNew = UUID.randomUUID().toString().replace("-", "") + suffixName;
        //保存图片
        if (!FileUtil.uploadImage(file,path,fileNameNew)) {
            log.warn("书籍封面上传失败");
            return ResponseResult.failed("书籍封面上传失败");
        }
        //删除原来的图片
        String cover1 = book.getCover();
        String fileNameOld = cover1.substring(cover1.lastIndexOf(File.separator) + 1);
        log.info("删除文件{}",fileNameOld);
        int flag = FileUtil.deleteFile(path, fileNameOld);
        if( flag == 0){
            log.warn("书籍原封面删除失败");
            FileUtil.deleteFile(path,fileNameNew);
            return ResponseResult.failed("书籍封面更新失败，原封面删除失败");
        }
        String cover = File.separator  + "images"
                + File.separator  + "bookCover"
                + File.separator + fileNameNew;
        try {
            Book book1 = new Book();
            book1.setBookId(bookId);
            book1.setCover(cover);
            bookDao.updateById(book1);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RollBackException("上传书籍封面失败");
        }
        book.setCover(cover);
        return ResponseResult.success("书籍封面上传成功",book);
    }

    @Override
    public ResponseResult getAllSlideShow() {
        try {
            List<SlideShow> books = slideShowDao.selectList(null);
            return ResponseResult.success("获取成功",books);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("获取所有轮播图失败");
            throw new RollBackException("获取轮播图失败，请刷新");
        }
    }

    @Override
    public ResponseResult saveSlideShow(MultipartFile file, int bookId) {
        Book book = bookDao.selectById(bookId);
        if(book == null){
            log.info("新增轮播图：相关书籍不存在");
            return ResponseResult.failed("相关书籍不存在");
        }
        ApplicationHome applicationHome = new ApplicationHome(SpringSecurityTestApplication.class);
        //将文件保存在当前项目同目录中的images中
        //打包前是当前java文件目录下，打包后是在项目目录下
        String path = applicationHome.getDir().getAbsolutePath()
                + File.separator  + "images"
                + File.separator  + "bookCover"
                + File.separator  + "slideShow";

        if(file.isEmpty()){
            return ResponseResult.failed("文件为空");
        }

        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String fileNameNew = UUID.randomUUID().toString().replace("-", "") + suffixName;
        //保存图片
        boolean flag = FileUtil.uploadImage(file, path, fileNameNew);
        if (!flag) {
            log.warn("轮播图上传失败");
            return ResponseResult.failed("轮播图上传失败");
        }
        String cover = File.separator  + "images"
                + File.separator  + "bookCover"
                + File.separator  + "slideShow"
                + File.separator + fileNameNew;
        try {
            SlideShow slideShow = new SlideShow();
            slideShow.setImgUrl(cover);
            slideShow.setBookId(bookId);
            slideShowDao.insert(slideShow);
            log.info("新增轮播图成功：{}",slideShow);
            return ResponseResult.success("新增轮播图成功",slideShow);
        } catch (Exception e) {
            //新增失败，删除存储的图片
            if (flag) {
                FileUtil.deleteFile(path, fileNameNew);
            }
            e.printStackTrace();
            log.warn("新增轮播图失败");
            throw new RollBackException("新增轮播图失败");
        }
    }

    @Override
    public ResponseResult deleteSlideShow(int showId) {
        try {
            SlideShow slideShow = slideShowDao.selectById(showId);
            if(slideShow == null){
                log.warn("删除轮播图：轮播图不存在");
                return ResponseResult.failed("轮播图删除失败，请刷新");
            }
            //删除图片文件
            ApplicationHome applicationHome = new ApplicationHome(SpringSecurityTestApplication.class);
            //将文件保存在当前项目同目录中的images中
            //打包前是当前java文件目录下，打包后是在项目目录下
            String path = applicationHome.getDir().getAbsolutePath()
                    + File.separator  + "images"
                    + File.separator  + "bookCover"
                    + File.separator  + "slideShow";
            String imgUrl = slideShow.getImgUrl();
            String fileName = imgUrl.substring(imgUrl.lastIndexOf(File.separator) + 1);
            FileUtil.deleteFile(path, fileName);
            //删除数据库数据
            slideShowDao.deleteById(showId);
            return ResponseResult.success("轮播图删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("删除轮播图失败");
            throw new RollBackException("删除轮播图失败");
        }
    }
}
